/**
* 通过todo-list的例子，了解HTTP方法-GET，POST，DELETE以及PUT
* 
**/

var http = require('http');
var url = require('url')

var items = [];

http.createServer(function(req,res) {
  switch (req.method){
    case 'POST':
      var item = '';
      req.setEncoding('utf8');
      req.on('data', function(chunk){
        item += chunk;
      });
      req.on('end',function(){
        items.push(item);
        res.end('add success！\n','utf8');
      });
      break;
    case 'GET':
      for (var i =0 ; i < items.length ; i ++){
        res.write(i + ') ' + items[i] + '\n','utf8');
      }
      res.end();
      break;
    case 'DELETE':
      var pathname = url.parse(req.url).pathname;
      var i = parseInt(pathname.slice(1) , 10);
      if (isNaN(i)){
        res.statusCode = 400;
        res.end('Invalid item id！\n');
      }else if (!items[i]){
        res.statusCode = 404;
        res.end('Item not found！\n');
      }else{
        items.splice(i , 1);
        res.end('delete success！\n');
      }
      break;
  }


}).listen(9000);

console.log('Your server is started @9000');